package cn.whitecao.agent.server.service.impl.mysql;

import cn.hutool.json.JSONUtil;
import cn.whitecao.agent.server.entity.Span;
import cn.whitecao.agent.server.mapper.SpanMapper;
import cn.whitecao.agent.server.model.CollectDataModel;
import cn.whitecao.agent.server.service.SpanService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
 * @author : BashfulHuang
 **/
@Service
public class MysqlSpanServiceImpl extends ServiceImpl<SpanMapper, Span>  implements SpanService {

    /**
     * 批量存储
     * @param collections 收集到的数据
     */
    @Override
    public void batchSave(Collection<CollectDataModel> collections){
        List<Span> spanList = collections.stream().map(c -> {
            Span span = new Span();
            BeanUtils.copyProperties(c,span);
            span.setStartTime(new Date(c.getStartTime()));
            span.setEndTime(new Date(c.getEndTime()));
            String jsonStr = JSONUtil.toJsonStr(c.getDataItems());
            span.setDataItems(jsonStr);
            return span;
        }).collect(Collectors.toList());
        super.saveBatch(spanList);
    }

    /**
     * 查询
     *
     * @param type      null不指定
     * @param startTime 开始时间戳
     * @param endTime   结束时间戳
     * @param traceId   traceId
     * @return list
     */
    @Override
    public List<Span> query(String type, Long startTime, Long endTime, String traceId) {
        QueryWrapper<Span> spanQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(type)){
            spanQueryWrapper.eq("type",type);
        }

        return null;
    }
}
